package com.cskaoyan.shiro;

import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WxRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;

        String username = token.getUsername();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andStatusEqualTo((byte) 0);

        List<User> users = userMapper.selectByExample(userExample);
        User user = users.size() >= 1 ? users.get(0) : null;
        String credential = userMapper.selectPasswordByName(username);

        if(credential==null){
            throw new UnknownAccountException("用户不存在！");
        }

        ByteSource salt = ByteSource.Util.bytes(username);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, credential,salt, this.getName());
        return authenticationInfo;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
